    //
//  DeviceView.m
//  GKBHouse
//
//  Created by  on 12-6-21.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DeviceView.h"
#import "GKBMainController.h"
#import "OperationTip.h"
#import "DecodeViewController.h"
#import "NewCloudViewController.h"
#import "BedViewController.h"
#import "TaTaMiViewController.h"
#import "ClothViewController.h"
#import "ShoesViewController.h"
@interface DeviceView()
@property (nonatomic,copy) NSDate * curDate;
- (void)openDeviceController;
- (void)openLight;
- (void)openACController;
- (void)openDrapes;
- (void)openDVD;
- (void)openMUSIC;
- (void)openTV;
@end
@implementation DeviceView
@synthesize button, title, type, equipment, Switch ,oldname ,oldpasswd;
@synthesize viewController;

- (id)initWithFrame:(CGRect)frame withEqu:(NewEquipment *)equ
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.equipment = equ;
        DeviceType dType = [equ.type intValue];
        
//        if (dType == 9) {
//            dType = DeviceTypeProtect;
//        }
        
        self.type = dType;
        NSString *name = equ.name;
       // NSString *name = [DeviceView deviceName:dType];
        NSString *imgName = [DeviceView deviceImageName:dType];
        UIButton *device = [UIButton buttonWithType:UIButtonTypeCustom];
        [device setFrame:CGRectMake(kIconBetween, 0, kIconWidth, kIconHeight)];
        [device setBackgroundImage:[UIImage imageNamed:@"lightBlue.png"] forState:UIControlStateNormal];
        [device setBackgroundImage:[UIImage imageNamed:@"green.png"] forState:UIControlStateSelected];
        [device setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
        [device addTarget:self action:@selector(openDeviceController) forControlEvents:UIControlEventTouchUpInside];
        self.button = device;
        [self addSubview:device];
       // [device release];
        
        UILabel *textLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, kIconHeight, kTextWidth, kTextHeight)];
        [textLabel setBackgroundColor:[UIColor clearColor]];
        [textLabel setTextColor:[UIColor whiteColor]];
        [textLabel setTextAlignment:UITextAlignmentCenter];
        [textLabel setFont:[UIFont boldSystemFontOfSize:16.0]];
        [textLabel setText:name];
        self.title = textLabel;
        [self addSubview:textLabel];
        [textLabel release];
        
        //场景添加长按事件
//        if (self.type == DeviceTypeScene) {
//            //button长按事件
//            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
//            longPress.minimumPressDuration = 0.8; //定义按的时间
//            [self.button addGestureRecognizer:longPress];
//            [longPress release];
//        }
        
        if (dType == DeviceTypeProtect)
        {
//            [device setBackgroundImage:[UIImage imageNamed:@"protectOff.png"] forState:UIControlStateNormal];
//            [device setBackgroundImage:[UIImage imageNamed:@"protectOn.png"] forState:UIControlStateSelected];
            
            [device setImage:[UIImage imageNamed:@"protectOff.png"] forState:UIControlStateNormal];
            [device setImage:[UIImage imageNamed:@"protectOn.png"] forState:UIControlStateSelected];
        }
        
    }
    return self;
}

-(void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        NSLog(@"长按事件");
        [self closeScene];
//        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"消息" message:@"确定删除该模式吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
//        [alert show];
    }
}
- (void)setDeviceOn:(BOOL)on
{
    self.Switch = on;
    self.button.selected = on;
    if (on) {        
//        [self.button setBackgroundImage:[UIImage imageNamed:@"green.png"] forState:UIControlStateNormal];
        self.equipment.state = kStateON;
    }
    else
    {
//        [self.button setBackgroundImage:[UIImage imageNamed:@"lightBlue.png"] forState:UIControlStateNormal];
        self.equipment.state = kStateOFF;
    }
    
    
    [self updateProtectName];
    
}

- (void)updateProtectName
{
    if (self.equipment.type.integerValue == DeviceTypeProtect)//DeviceTypeProtect
    {
        if (self.equipment.protectId == 0) {
            if (self.button.selected == NO) {
                self.title.text = @"撤防";
            }
            else
            {
                self.title.text = @"布防";
            }
        }
        else
        {
            NSString *bufang = [@"布防" stringByAppendingFormat:@"%d", self.equipment.protectId];
            NSString *cefang = [@"撤防" stringByAppendingFormat:@"%d", self.equipment.protectId];
            if (self.button.selected == NO) {
                self.title.text = cefang;
            }
            else
            {
                self.title.text = bufang;
            }
        }
    }
    if (self.equipment.type.integerValue == DeviceTypeArea)
    {
        if ([self.equipment.switchId isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"hostnum"]]) {
            self.button.userInteractionEnabled = NO;
            [self.button setImage:[UIImage imageNamed:@"dinwei1"] forState:UIControlStateNormal];
            
        }else{
            self.button.userInteractionEnabled = YES;
            
        }
    }
}

+ (void)setDeivceOnOff:(NewEquipment *)euq button:(UIButton *)OnOff State:(BOOL)on
{
    if (on) {
        euq.state = kStateON;
        [OnOff setBackgroundImage:[UIImage imageNamed:@"green_normal.png"] forState:UIControlStateNormal];
        [OnOff setBackgroundImage:[UIImage imageNamed:@"green_click.png"] forState:UIControlStateHighlighted];
    }
    else
    {
        euq.state = kStateOFF;
        [OnOff setBackgroundImage:[UIImage imageNamed:@"redNormal.png"] forState:UIControlStateNormal];
        [OnOff setBackgroundImage:[UIImage imageNamed:@"redSelect.png"] forState:UIControlStateHighlighted];
    }
}
+ (NSString *)deviceName:(DeviceType)dType
{
    switch (dType) {
        case DeviceTypeLight:
            return @"灯";
            break;
        case DeviceTypeDrapes:
            return @"窗帘";
            break;
        case DeviceTypeTV:
            return @"电视";
            break;
        case DeviceTypeDVD:
            return @"DVD";
            break;
        case DeviceTypeScene:
            return @"背景音乐";
            break;
        case DeviceTypeMusic:
            return @"背景音乐";
            break;
        case DeviceTypeAC:
            return @"空调";
            break;
        
        default:
            return @"NULL";
            break;
    }
}
+ (NSString *)deviceImageName:(DeviceType)dType
{
    switch (dType) {

        case DeviceTypeLight:
            return @"light.png";
            break;
        case DeviceTypeDrapes:
            return @"drapes.png";
            break;
        case DeviceTypeTV:
            return @"TV.png";
            break;
        case DeviceTypeDVD:
            return @"DVD.png";
            break;
        case DeviceTypeScene:
            return @"TV.png";
            break;
        case DeviceTypeMusic:
            return @"scene.png";
            break;
        case DeviceTypeAC:
            return @"AC.png";
            break;
            
        case DeviceTypeSwitchAir:
            return @"changeAir.png";
            break;
        case DeviceTypeWater:
            return @"watering.png";
            break;
        case DeviceTypeOther:
            return @"other.png";
            break;
//        case DeviceTypeScene:
//            return @"scene.png";
        case DeviceTypeAll:
            return @"allOnOff.png";
            break;
        case DeviceTypeVideo:
            return @"video.png";
            break;
        case DeviceTypeArea:
            return @"dingwei@3x.png";
            break;
        case DeviceTypeProtect:
            return @"";
            break;
       
            
        
            
        case DeviceTypeDecode:
            return @"decode.png";
            break;
        case DeviceTypeNewCloud:
            return @"xinfengxitong.png";
            break;
        case DeviceTypeBed:
            return @"fanbanchuang.png";
            break;
        case DeviceTypeXClothStand:
            return @"xuanzhuanyijia.png";
            break;
        case DeviceTypeCloth:
            return @"yigui.png";
            break;
        case DeviceTypeTTM:
            return @"tatami.png";
            break;
        case DeviceTypeShoes:
            return @"xiegui.png";
            break;
        case DeviceTypeCClothStand:
            return @"liangyijia.png";
            break;
       
            
        default:
            return @"NULL";
            break;
    }
}
- (void)openDeviceController
{
    if (self.type == DeviceTypeProtect) {
        [self openProtect];
        return;
    }
    
    if ([self NORegulate]) {
        return;
    }
    
    
    switch (self.type) {
            
        case DeviceTypeLight:
            //暂停定时器
            [GKBMainController postStopRefresh];
            [self openLight];
            break;
        case DeviceTypeDrapes:
            //暂停定时器
            [GKBMainController postStopRefresh];
            [self openDrapes];
            break;
        case DeviceTypeTV:
            //暂停定时器
            [GKBMainController postStopRefresh];
            [self openTV];
            break;
        case DeviceTypeDVD:
            //暂停定时器
            [GKBMainController postStopRefresh];
            [self openDVD];
            break;
        case DeviceTypeAC:
            //暂停定时器
            [GKBMainController postStopRefresh];
            [self openACController];
            break;
            
        case DeviceTypeScene:
            [GKBMainController postStopRefresh];
            [self openScene];
            break;
        case DeviceTypeMusic:
            [GKBMainController postStopRefresh];
            [self openMUSIC];
            break;
        case DeviceTypeAll:
            [self allOnOffAction];
            break;
            
        case DeviceTypeVideo:
            [self openVideo];
            break;
        case DeviceTypeArea:
            [self openArea];
            break;
        case DeviceTypeDecode:
            [GKBMainController postStopRefresh];
            [self openDecode];
            break;
            
        case DeviceTypeNewCloud:
            [GKBMainController postStopRefresh];
            [self openNewCloud];
            break;
        case DeviceTypeBed:
        [GKBMainController postStopRefresh];
            [self openBed];
            break;
        case DeviceTypeCloth:
            [GKBMainController postStopRefresh];
            [self openCloth];
            break;
        case DeviceTypeTTM:
            [GKBMainController postStopRefresh];
            [self openTTM];
            break;
        case DeviceTypeShoes:
            [GKBMainController postStopRefresh];
            [self openShoes];
            break;
        default:
            
            break;
    } 
}
//- (BOOL)NORegulate
//{
//    if ([self.equipment.regulate isEqualToString:kNORegulate]) {
//        [DeviceView ctlDevice:self.equipment target:self end:@selector(ctlDeviceEnd:)];
//        return YES;
//    }
//    return NO;
//}
- (void)openLight
{
    LightController *lightController = [[LightController alloc]initWithEquipment:self.equipment];
    
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:lightController.view];
    self.viewController = lightController;
    [lightController release];
}
- (void)openACController
{
    ACController *AC = [[ACController alloc]initWithEquipment:self.equipment];
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:AC.view];
    self.viewController = AC;
    [AC release];
}
- (void)openDrapes
{
    DrapesController *Drape = [[DrapesController alloc]initWithEquipment:self.equipment];
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:Drape.view];
    self.viewController = Drape;
    [Drape release];
}
- (void)openDVD
{
    DVDController *DVD = [[DVDController alloc]initWithEquipment:self.equipment];
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:DVD.view];
    self.viewController = DVD;
    [DVD release];
}

- (void)openMUSIC
{
//    MUSICController *MUSIC = [[MUSICController alloc]initWithEquipment:self.equipment];
//    UIView *mainView = [GKBMainController mainView];
//    [mainView addSubview:MUSIC.view];
//    self.viewController = MUSIC;
//    [MUSIC release];
}
- (void)openTV
{
    TVController *TV = [[TVController alloc]initWithEquipment:self.equipment];
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:TV.view];
    self.viewController = TV;
    [TV release];
}
- (NSArray *)closeIdArray:(NewEquipment *)scene
{
    NSArray *openIDs = scene.openEques;
    NSInteger sceneId = [scene.switchId integerValue];
    GKBMainController *main = [GKBMainController mainCtr];
    NSMutableArray *closeIDs = [NSMutableArray array];
    for (NewEquipment *equ in main.sceneArray) {
        if (sceneId != equ.switchId.integerValue) {
            for (NSString *openId in equ.openEques) {
                if (![openIDs containsObject:openId]) {
                    [closeIDs addObject:openId];
                }
            }

        }
    }
    return closeIDs;
}
//情景
- (void)openScene
{
    NSString *tipStart = [OperationTip startOperat:YES name:self.equipment.name];
    [iToast showTip:tipStart gravity:iToastGravityBottom];
    
    
    NSString *openStr = [self.equipment.openEques componentsJoinedByString: @","];
    NSArray *closeArray = [self closeIdArray:self.equipment];
   
    NSString *closeStr = [closeArray componentsJoinedByString: @","];
     NSLog(@"%@", closeStr);

    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sceneid\":\"1\", \"opensidstr\":\"%@\", \"closesidstr\":\"%@\", \"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, openStr, closeStr, sessionId];
    [WebServices setShowConnectting:NO];  
    
    NSString *errorTip = [OperationTip operat:self.equipment.name open:YES result:NO errorType:ErrorTypeNetworkFail];
    [WebServices requestStartOrder:@"ctlScene" body:body target:self action:@selector(openSceneEnd:) errorTip:errorTip];
}
- (void)openSceneEnd:(NSDictionary *)dic
{
    NSLog(@"%@",dic);
    if (self.equipment == nil) {//后台刷新电器状态，更新状态，已重载电器，此电器已释放
        NSLog(@"nil");
        return;
    }
    NSNumber *result = [dic objectForKey:@"result"];
    NSString *tip = @"";
    if (result.integerValue == 0) {   
        tip = [OperationTip operat:self.equipment.name open:YES result:YES errorType:ErrorTypeServerReturnFail];
//            [self setScene];
            [GKBMainController refreshDevices];
        
        [self updateEquipmentState];
        
    }
    else
    {
        tip = [OperationTip operat:self.equipment.name open:YES result:NO errorType:ErrorTypeServerReturnFail];
    }
    [iToast showTip:tip gravity:iToastGravityBottom];
}
- (void)setScene
{
    GKBMainController *main = [GKBMainController mainCtr];
    NSMutableArray *openIDs = self.equipment.openEques;   
    NSArray *closeArray = [self closeIdArray:self.equipment];
    NSMutableArray *closeIDs = [NSMutableArray arrayWithArray:closeArray];
    for (NSString *key in main.rooms) {
        if (![key isEqualToString:NSLocalizedString(@"scene", nil)]) {//不是情景，全部设置关
            NSArray *array = [main.rooms objectForKey:key];
            for (NewEquipment *equ in array) {
                NSString *switchId = equ.switchId;
                if ([openIDs containsObject:switchId]) {//是开的电器
                    [equ setState:kStateON];
                }
                if ([closeIDs containsObject:switchId]) {
                    [equ setState:kStateOFF];
                }
               
            }
        }
    }
}
//情景
- (void)closeScene
{
    NSString *tipStart = [OperationTip startOperat:NO name:self.equipment.name];
    [iToast showTip:tipStart gravity:iToastGravityBottom];
    
    
    NSString *closeArray = [self.equipment.openEques componentsJoinedByString: @","];
    
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sceneid\":\"1\", \"opensidstr\":\"\", \"closesidstr\":\"%@\", \"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, closeArray, sessionId];
    [WebServices setShowConnectting:NO];  
    
    NSString *errorTip = [OperationTip operat:self.equipment.name open:NO result:NO errorType:ErrorTypeNetworkFail];
    [WebServices requestStartOrder:@"ctlScene" body:body target:self action:@selector(closeSceneEnd:) errorTip:errorTip];
}
- (void)closeSceneEnd:(NSDictionary *)dic
{
    NSLog(@"%@",dic);
    if (self.equipment == nil) {//后台刷新电器状态，更新状态，已重载电器，此电器已释放
        NSLog(@"nil");
        return;
    }
    NSNumber *result = [dic objectForKey:@"result"];
    NSString *tip = @"";
    if (result.integerValue == 0) {   
        tip = [OperationTip operat:self.equipment.name open:NO result:YES errorType:ErrorTypeServerReturnFail];
        [self setCloseScene];
        [GKBMainController refreshDevices];
        
        [self updateEquipmentState];
    }
    else
    {
        tip = [OperationTip operat:self.equipment.name open:NO result:NO errorType:ErrorTypeServerReturnFail];
    }
    [iToast showTip:tip gravity:iToastGravityBottom];
}
- (void)setCloseScene
{
    GKBMainController *main = [GKBMainController mainCtr];
    NSMutableArray *closeArray = self.equipment.openEques;   

    for (NSString *key in main.rooms) {
        if (![key isEqualToString:NSLocalizedString(@"scene", nil)]) {//不是情景，全部设置关
            NSArray *array = [main.rooms objectForKey:key];
            for (NewEquipment *equ in array) {
                NSString *switchId = equ.switchId;
                if ([closeArray containsObject:switchId]) {//是开的电器
                    [equ setState:kStateOFF];
                }
                
            }
        }
    }
}
- (void)allOnOffAction
{
    NSString *tipStart = NSLocalizedString(@"All the electrical is turning off!", nil);// [OperationTip startOperat:NO name:self.equipment.name];
    [iToast showTip:tipStart gravity:iToastGravityBottom];
    
    //只提供全关
    NSString *order = @"";
    NSString *switchId = @"1";// self.equipment.switchId;
    NSString *sessionId = [LoginController1 sessionID];
    order = @"ALLCLOSE";
    
    NSString *fomat = @"[{\"orderId\":\"%@\", \"switchId\":\"%@\", \"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, order, switchId, sessionId];
    //[iToast showTip:tipStart gravity:iToastGravityBottom];
    [WebServices setShowConnectting:NO];  
    
    NSString *errorTip = [OperationTip operat:self.equipment.name open:NO result:NO errorType:ErrorTypeNetworkFail];
    [WebServices requestStartOrder:@"ctlDevice" body:body target:self action:@selector(allOnOffActionEnd:) errorTip:errorTip];
}
- (void)allOnOffActionEnd:(NSDictionary *)dic
{
    NSLog(@"%@",dic);
    if (self.equipment == nil) {//后台刷新电器状态，更新状态，已重载电器，此电器已释放
        NSLog(@"nil");
        return;
    }
    NSNumber *result = [dic objectForKey:@"result"];
    NSString *tip = @"";
    if (result.integerValue == 0) {   
        tip = NSLocalizedString(@"All the electrical turn off success!", nil);// [OperationTip operat:self.equipment.name open:YES result:YES errorType:ErrorTypeServerReturnFail];
            [self turnOffAll];
        [self updateEquipmentState];
        
    }
    else
    {
        tip = NSLocalizedString(@"All the electrical turn off fail!", nil);//[OperationTip operat:self.equipment.name open:NO result:YES errorType:ErrorTypeServerReturnFail];
    }
    [iToast showTip:tip gravity:iToastGravityBottom];
}
- (void)turnOffAll
{
    GKBMainController *mainctr = [GKBMainController mainCtr];
    if (mainctr) {
        if (mainctr.rooms) {
            for (NSString *key in mainctr.rooms) {
                if (![key isEqualToString:NSLocalizedString(@"scene", nil)]) {//不是情景，全部设置关
                    NSArray *array = [mainctr.rooms objectForKey:key];
                    for (NewEquipment *equ in array) {
                        equ.state = kStateOFF;
                    }
                }
            }
            
            //关闭布防
            NSArray *array = mainctr.videoArray;
            for (NewEquipment *equ in array) {
                equ.state = kStateOFF;
            }
        }
    }
    
    [GKBMainController refreshDevices];
}

- (void)openArea
{
    
    NSString *name = self.equipment.relevanceUserName;
    NSString *passwd = self.equipment.relevanceUserPass;
    _hostnum = self.equipment.switchId;
    NSString *fomate = @"[{\"username\":\"%@\", \"userpassword\":\"%@\"}]";
    NSString *json = [NSString stringWithFormat:fomate, name, passwd];
    NSString *order = @"login";
    NSString *loginError = NSLocalizedString(@"LoginFail", nil);
    NSString *errorType = [OperationTip errorType:ErrorTypeNetworkFail];
    NSString *errorTip = [NSString stringWithFormat:@"%@, %@", loginError, errorType];
    [WebServices setShowConnectting:YES];
    [WebServices requestStartOrder:order body:json target:self action:@selector(loginEnd:) errorTip:errorTip];
}

- (void)loginEnd:(NSDictionary *)dic
{
    
    NSLog(@"%@", dic);
    NSString *result = [dic objectForKey:@"result"];
    NSString *sessionId = [dic objectForKey:@"sessionId"];
    _sessionIds = sessionId;
    if ([result isEqualToString:@"0"]) {
        [LoginController1 setSessionID:sessionId];
//        NSString *userName = [LoginController1 currentUser];
//        [AppFile saveSuccessLoginUser:userName];//保存成功登录用户名到文件
        
        [self ping];
        
    }
    else
    {
        NSString *loginError = NSLocalizedString(@"Login fail!Fill in the correct information!", nil);
        [iToast showTip:loginError gravity:iToastGravityCenter];
        [LoginController1 setAutoLogin:NO];
        [[GKBMainController mainCtr] dismissView];
    }
    
}


- (void)ping
{
    NSLog(@"ping");
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, sessionId];
    [WebServices requestStartOrder:@"ping" body:body target:self action:@selector(pingEnd:) errorTip:nil];
}

- (void)pingEnd:(NSDictionary *)dic
{
    NSLog(@"%@", dic);
    NSString *result = [dic objectForKey:@"result"];
    NSString *state = [dic objectForKey:@"state"];
    if ([result isEqualToString:@"0"])
    {
        if ([state isEqualToString:@"online"])
        {
            [[NSUserDefaults standardUserDefaults] setObject:_sessionIds forKey:@"sessionIds"];
            [[NSUserDefaults standardUserDefaults] setObject:_hostnum forKey:@"hostnum"];
            [[GKBMainController mainCtr]loadList];
            
            return;
        }
    }  
//        [LoginController1 setAutoLogin:NO];
    
    //主机不在线情况
    NSString *errorTip = NSLocalizedString(@"Host is not online!", nil);
    [iToast showTip:errorTip gravity:iToastGravityBottom];
    NSString *seseinoId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionIds"];
    [LoginController1 setSessionID:seseinoId];

}

- (void)openVideo
{
//    NSString *string = @"p2pcamlive://com.tutk.p2pcamlive?tabIdx:0";
    
    if (self.equipment.target && self.equipment.selector) {
        NSLog(@"======%@=====",self.equipment);
        [self.equipment.target performSelector:self.equipment.selector withObject:self.equipment];
        return;
    }
    NSString *string = @"objectp2pipcam:";
    NSURL *url = [NSURL URLWithString:string];
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication]openURL:url];
    }
    else
    {
        //下载界面
//        string = @"https://itunes.apple.com/cn/app/ipcam-f3/id663276197?mt=8";
        string = @"https://itunes.apple.com/cn/app/gkb-shi-pin-jian-kong/id787017884?mt=8";//新
        url = [NSURL URLWithString:string];
        [[UIApplication sharedApplication]openURL:url];
//        [iToast showTip:NSLocalizedString(@"video open error", nil) gravity:iToastGravityBottom];
    }
    
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/
- (void)removeFromSuperview
{
    self.equipment = nil;
   // self.viewController = nil;
    self.button = nil;
    self.title = nil;
    [super removeFromSuperview];
}
+ (BOOL)deviceStateOn:(NewEquipment *)equ
{
    if([equ.state isEqualToString: kStateON])
    {
        return YES;
    }
    if([equ.state isEqualToString: kStateOFF])
    {
        return NO;
    }
    return NO;
}
- (void)updateEquipmentState
{
    GKBMainController *main = [GKBMainController mainCtr];
    [main updateStateByNet];
}
#pragma mark - 电器设备开关状态
- (void)ctlDeviceEnd:(NSDictionary *)dic
{
 //   NSLog(@"%@", dic);
    if (self.equipment == nil) {//后台刷新电器状态，更新状态，已重载电器，此电器已释放
        NSLog(@"nil");
        return;
    }
//    NSLog(@"%@", dic);
    NSString *tip = @"";
    BOOL OPEN = [DeviceView deviceStateOn:self.equipment];
    BOOL STATE = !OPEN;
    NSNumber *result = [dic objectForKey:@"result"];
    if (result.integerValue == 0) {
        
        tip = [OperationTip operat:self.equipment.name open:STATE result:YES errorType:ErrorTypeServerReturnFail]; 
        [self setDeviceOn:STATE];
        
        GKBMainController *main = [GKBMainController mainCtr];        
        [main updateStateByNet];
    }
    else
    {
        tip = [OperationTip operat:self.equipment.name open:STATE result:NO errorType:ErrorTypeServerReturnFail];
    }
    
    [iToast showTip:tip gravity:iToastGravityBottom];
}
+ (void)ctlDeviceSwithcId:(NSString *)swId name:(NSString *)name OnOff:(BOOL)open target:(id)target end:(SEL)action
{
    NSString *order = @"";
    NSString *switchId = swId;
    if (open) {
        order = @"OPEN";
    }
    else
    {
        order = @"CLOSE";
    }

    NSString *tipStart = [OperationTip startOperat:open name:name];
    [iToast showTip:tipStart gravity:iToastGravityBottom];
    
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"orderId\":\"%@\", \"switchId\":\"%@\", \"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, order, switchId, sessionId];
    
    [WebServices setShowConnectting:NO];  

    NSString *errorTip = [OperationTip operat:name open:open result:NO errorType:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"ctlDevice" body:body target:target action:action errorTip:errorTip];
}

//提示，操作：xxx, 
+ (void)OperatSwithcId:(NSString *)swId name:(NSString *)name OnOff:(BOOL)open target:(id)target end:(SEL)action
{
    NSString *order = @"";
    NSString *switchId = swId;
    if (open) {
        order = @"OPEN";
    }
    else
    {
        order = @"CLOSE";
    }
    //操作：xxx
    NSString *orderStr = order.lowercaseString;
    NSString *orderName = NSLocalizedString(orderStr, nil);
    NSString *operat = NSLocalizedString(@"operat:", nil);
    NSString *startTip = [operat stringByAppendingString:orderName];
    [iToast showTip:startTip gravity:iToastGravityBottom];
    
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"orderId\":\"%@\", \"switchId\":\"%@\", \"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, order, switchId, sessionId];

    [WebServices setShowConnectting:NO];  
    
    //操作失败！原因：
    NSString *errorTip = [OperationTip operatSuccess:NO type:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"ctlDevice" body:body target:target action:action errorTip:errorTip];
}
+ (void)ctlDevice:(NewEquipment *)equ target:(id)target end:(SEL)action
{
    NSString *order = @"";
    NSString *switchId = equ.switchId;
    BOOL OPEN = NO;
    if([equ.state isEqualToString: kStateON])
    {
        OPEN = NO;
        order = @"CLOSE";
    }
    if([equ.state isEqualToString: kStateOFF])
    {
        OPEN = YES; 
        order = @"OPEN";
    }
    [DeviceView ctlDeviceSwithcId:switchId name:equ.name OnOff:OPEN target:target end:action];
    
}
+ (NSString *)ctlDeviceStr:(BOOL)on name:(NSString *)name
{
    NSString *tipType = @"";
    if(on)
    {
        tipType = NSLocalizedString(@"opening", nil);
    }
    else
    {
        tipType = NSLocalizedString(@"closing", nil);
    }
    // xxx，正在打开；xxx，正在关闭
    NSString *tip = [NSString stringWithFormat:@"%@,%@", name, tipType];
    
    return tip;
}
+ (NSString *)ctlDeviceEndTipStr:(BOOL)on name:(NSString *)name
{
    NSString *tipType = @"";
    
    if (on) {
        tipType = NSLocalizedString(@"open", nil);
    }
    else
    {
        tipType = NSLocalizedString(@"close", nil);
    }
    NSString *tip = [NSString stringWithFormat:@"%@,%@", name, tipType];
    return tip;
}

#pragma mark - 安防操作

- (void)openProtect
{
    NSString *order = @"";
    NSString *switchId = self.equipment.switchId;
    NSString *name = @"";
    BOOL OPEN = [DeviceView deviceStateOn:self.equipment];
    
    if (OPEN == NO) {//打开布防用open,打开撤防用close
        order = @"OPEN";
        name = NSLocalizedString(@"security_off", nil);
    }
    else
    {
        order = @"CLOSE";
        name = NSLocalizedString(@"security_on", nil);
    }
    
    if (self.equipment.protectId > 0) {
        name = [name stringByAppendingFormat:@"%d", self.equipment.protectId];
    }
    
    NSString *tipStart = [OperationTip startOperat:YES name:name];
    
    [iToast showTip:tipStart gravity:iToastGravityBottom];
    
    NSString *sessionId = [LoginController1 sessionID];
    NSString *fomat = @"[{\"orderId\":\"%@\", \"switchId\":\"%@\", \"sessionId\":\"%@\"}]";
    NSString *body = [NSString stringWithFormat:fomat, order, switchId, sessionId];
    
    [WebServices setShowConnectting:NO];
    
    NSString *errorTip = [OperationTip operat:self.title.text open:YES result:NO errorType:ErrorTypeNetworkFail];
    
    [WebServices requestStartOrder:@"ctlDevice" body:body target:self action:@selector(openProtectEnd:) errorTip:errorTip];
}

- (void)openProtectEnd:(NSDictionary *)dic
{
    //   NSLog(@"%@", dic);
    if (self.equipment == nil) {//后台刷新电器状态，更新状态，已重载电器，此电器已释放
        NSLog(@"nil");
        return;
    }
    NSString *tip = @"";
    BOOL OPEN = [DeviceView deviceStateOn:self.equipment];
    BOOL STATE = !OPEN;
    NSNumber *result = [dic objectForKey:@"result"];
    if (result.integerValue == 0) {
        
        [self setDeviceOn:STATE];
        GKBMainController *main = [GKBMainController mainCtr];
        [main updateStateByNet];
        
//        tip = [OperationTip operat:self.title.text open:YES result:YES errorType:ErrorTypeServerReturnFail];
        
        NSString *operat = @"";
        
        if (STATE == YES) {//布防中
            operat = @"布防";
            operat = NSLocalizedString(@"security_on", nil);
        }
        else
        {
            operat = @"撤防";
            operat = NSLocalizedString(@"security_off", nil);
        }
        NSString *operatResult = @"";
        operatResult = NSLocalizedString(@"success", nil);

        tip = [NSString stringWithFormat:@"%@%@",operat, operatResult];
        
    }
    else
    {
        tip = [OperationTip operat:self.title.text open:YES result:NO errorType:ErrorTypeServerReturnFail];
        
        NSString *operat = @"";

        if (STATE == YES) {//已布防
            operat = @"撤防";//将进行的操作是撤防
            operat = NSLocalizedString(@"security_off", nil);
        }
        else
        {
            operat =  @"布防";//将进行的操作是布防
            operat = NSLocalizedString(@"security_on", nil);
        }
        NSString *operatResult = @"";
        operatResult =  NSLocalizedString(@"failure!cause:", nil);
        
        tip = [NSString stringWithFormat:@"%@%@",operat, operatResult];
    }
    
    [iToast showTip:tip gravity:iToastGravityBottom];
}

#pragma mark - 90

- (void)openDecode
{
    DecodeViewController *Decode = [[DecodeViewController alloc]initWithEquipment:self.equipment];
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:Decode.view];
    self.viewController = Decode;
    [Decode release];
}

- (void)openNewCloud
{
    NewCloudViewController *NewCloud = [[NewCloudViewController alloc] initWithEquipment:self.equipment];
    
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:NewCloud.view];
    self.viewController = NewCloud;
    [NewCloud release];
}

- (void)openBed
{
    BedViewController *bed = [[BedViewController alloc] initWithEquipment:self.equipment];
    
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:bed.view];
    self.viewController = bed;
    [bed release];
}
- (void)openCloth
{
    ClothViewController *cloth = [[ClothViewController alloc] initWithEquipment:self.equipment];
    
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:cloth.view];
    self.viewController = cloth;
    [cloth release];
}
- (void)openTTM
{
    TaTaMiViewController *ttm = [[TaTaMiViewController alloc] initWithEquipment:self.equipment];
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:ttm.view];
    self.viewController = ttm;
    [ttm release];
    
}
- (void)openShoes
{
    ShoesViewController *shoes = [[ShoesViewController alloc] initWithEquipment:self.equipment];
    
    UIView *mainView = [GKBMainController mainView];
    [mainView addSubview:shoes.view];
    self.viewController = shoes;
    [shoes release];
}
@end
